<template>
	<view class="warp">
		<!-- 自定义状态栏 -->
		<custom-status-bar gradient-type="chat"></custom-status-bar>
		
		<view class="header">
			<text class="header-title">交流区</text>
		</view>
		
		<!-- 搜索框 -->
		<view class="search-container">
			<input 
				class="search-input" 
				placeholder="搜索帖子内容..." 
				v-model="searchKeyword"
				@confirm="handleSearch"
			/>
			<button class="search-button" @click="handleSearch">搜索</button>
		</view>
		
		<!-- 悬浮发布按钮 -->
		<view class="float-publish-btn" @click="togglePublishWindow">
			<text class="float-publish-icon">+</text>
		</view>
		
		<!-- 发布消息区域（悬浮窗口） -->
		<view class="publish-window" :class="{ 'show': showPublishWindow }">
			<view class="publish-window-content">
				<view class="publish-window-header">
					<text class="publish-window-title">发布消息</text>
					<text class="publish-window-close" @click="togglePublishWindow">×</text>
				</view>
				<textarea 
					class="message-input" 
					v-model="newPostContent" 
					placeholder="分享你的想法..." 
					auto-height
				></textarea>
				<button class="post-button" @click="publishPost">发布</button>
			</view>
		</view>
		
		<!-- 横栏分类切换 -->
		<view class="category-tabs">
			<view 
				class="tab-item" 
				:class="{ active: activeCategory === 'chat' }"
				@click="switchCategory('chat')"
			>
				闲聊区
			</view>
			<view 
				class="tab-item" 
				:class="{ active: activeCategory === 'books' }"
				@click="switchCategory('books')"
			>
				购书区
			</view>
		</view>
		
		<!-- 帖子列表 -->
		<scroll-view 
			class="posts-scroll" 
			scroll-y="true" 
			@scrolltolower="onReachBottom"
			@scrolltoupper="onPullDownRefresh"
			:refresher-enabled="true"
			:refresher-triggered="refreshing"
			@refresherrefresh="onPullDownRefresh"
		>
			<view class="posts-container" v-if="activeCategory === 'chat'">
				<view class="post-item" v-for="(post, index) in displayedChatPosts" :key="index" @click="showPostDetail(post)">
					<view class="post-header">
						<image class="user-avatar" :src="post.avatar" mode="aspectFill"></image>
						<view class="user-info">
							<text class="username">{{ post.username }}</text>
							<text class="post-time">{{ post.time }}</text>
						</view>
					</view>
					<view class="post-content">
						<text class="post-title">{{ post.content }}</text>
						<image v-if="post.image" class="post-image" :src="post.image" mode="aspectFill"></image>
					</view>
					<view class="post-footer">
						<text class="post-date">{{ post.date }}</text>
						<view class="chat-action" @click.stop="chatWithUser(post)">
							<text>💬 私聊</text>
						</view>
					</view>
				</view>
				<view class="loading-text" v-if="chatLoading">{{ chatLoadingText }}</view>
			</view>
			
			<view class="posts-container" v-if="activeCategory === 'books'">
				<view class="post-item" v-for="(post, index) in displayedBookPosts" :key="index" @click="showPostDetail(post)">
					<view class="post-header">
						<image class="user-avatar" :src="post.avatar" mode="aspectFill"></image>
						<view class="user-info">
							<text class="username">{{ post.username }}</text>
							<text class="post-time">{{ post.time }}</text>
						</view>
					</view>
					<view class="post-content">
						<text class="post-title">{{ post.title }}</text>
						<image v-if="post.image" class="post-image" :src="post.image" mode="aspectFill"></image>
					</view>
					<view class="post-footer">
						<text class="post-date">{{ post.date }}</text>
						<view class="chat-action" @click.stop="chatWithUser(post)">
							<text>💬 私聊</text>
						</view>
					</view>
				</view>
				<view class="loading-text" v-if="bookLoading">{{ bookLoadingText }}</view>
			</view>
		</scroll-view>
		
		<!-- 帖子详情弹窗 -->
		<view class="post-detail-overlay" v-if="showDetail" @click="closePostDetail">
			<view class="post-detail-container" @click.stop>
				<view class="post-detail-header">
					<image class="detail-user-avatar" :src="selectedPost.avatar" mode="aspectFill"></image>
					<view class="detail-user-info">
						<text class="detail-username">{{ selectedPost.username }}</text>
						<text class="detail-post-time">{{ selectedPost.time }}</text>
					</view>
				</view>
				<view class="detail-post-content">
					<text class="detail-post-title">{{ selectedPost.title || selectedPost.content }}</text>
					<image v-if="selectedPost.image" class="detail-post-image" :src="selectedPost.image" mode="aspectFill"></image>
					<view class="detail-post-footer">
						<text class="detail-post-date">{{ selectedPost.date }}</text>
					</view>
				</view>
				<!-- 私聊按钮 -->
				<view class="chat-with-user" @click="chatWithUser(selectedPost)">
					<text>💬 联系TA</text>
				</view>
				<view class="close-button" @click="closePostDetail">关闭</view>
			</view>
		</view>
	</view>
</template>

<script>
	// #ifdef APP
	import customStatusBar from "@/components/custom-status-bar/custom-status-bar.vue";
	import bookPosts from "./bookPosts.json";
	// #endif
	export default {
		// #ifdef APP
		components: {
			customStatusBar
		},
		// #endif
		data() {
			return {
				bannerList:[],
				hasLogin: false,
				activeCategory: 'chat',
				// 搜索关键词
				searchKeyword: '',
				// 发布消息内容
				newPostContent: '',
				// 控制发布窗口显示
				showPublishWindow: false,
				// 帖子数据
				chatPosts: [
					{
						id: 1,
						username: '张三',
						avatar: '/static/avatar1.jpg',
						content: '有人一起去图书馆吗？下午2点',
						image: '',
						time: '10:20',
						date: '今天'
					},
					{
						id: 2,
						username: '李四',
						avatar: '/static/avatar2.jpg',
						content: '刚买的篮球鞋到了，超赞！',
						image: 'https://picsum.photos/id/96/400/300',
						time: '昨天 15:30',
						date: '昨天'
					}
				],
				bookPosts: bookPosts,
				// 分页显示
				displayedChatPosts: [],
				displayedBookPosts: [],
				chatPage: 1,
				bookPage: 1,
				pageSize: 10,
				refreshing: false,
				chatLoading: false,
				bookLoading: false,
				chatLoadingText: '加载中...',
				bookLoadingText: '加载中...',
				showDetail: false,
				selectedPost: {},
				// 搜索结果
				searchResults: []
			}
		},
		onShow() {
			this.hasLogin = uniCloud.getCurrentUserInfo().tokenExpired > Date.now()
		},
		onLoad() {
			this.loadInitialPosts();
		},
		methods: {
			switchCategory(category) {
				this.activeCategory = category;
				// 切换分类时清除搜索关键词
				this.searchKeyword = '';
				this.loadInitialPosts();
			},
			
			// 处理搜索
			handleSearch() {
				if (!this.searchKeyword.trim()) {
					// 如果搜索关键词为空，显示所有帖子
					this.loadInitialPosts();
					return;
				}
				
				// 根据当前分类进行搜索
				if (this.activeCategory === 'chat') {
					// 在闲聊区帖子中搜索
					const filteredPosts = this.chatPosts.filter(post => 
						post.content.includes(this.searchKeyword)
					);
					this.displayedChatPosts = filteredPosts.slice(0, this.pageSize);
				} else {
					// 在购书区帖子中搜索
					const filteredPosts = this.bookPosts.filter(post => 
						post.title.includes(this.searchKeyword)
					);
					this.displayedBookPosts = filteredPosts.slice(0, this.pageSize);
				}
				
				uni.showToast({
					title: '搜索完成',
					icon: 'success'
				});
			},
			
			// 切换发布窗口显示状态
			togglePublishWindow() {
				this.showPublishWindow = !this.showPublishWindow;
			},
			
			// 跳转到消息列表
			goToMessages() {
				uni.navigateTo({
					url: '/pages/friend/friend'
				});
			},
			
			// 跳转到私聊列表
			goToPrivateChatList() {
				uni.navigateTo({
					url: '/pages/friend/friend'
				});
			},
			
			// 发布新消息
			publishPost() {
				if (!this.newPostContent.trim()) {
					uni.showToast({
						title: '请输入内容',
						icon: 'none'
					});
					return;
				}
				
				// 创建新帖子
				const newPost = {
					id: this.chatPosts.length + 1,
					username: '我',
					avatar: '/static/my-avatar.png',
					content: this.newPostContent.trim(),
					image: '',
					time: this.getCurrentTime(),
					date: '今天'
				};
				
				// 添加到帖子列表
				this.chatPosts.unshift(newPost);
				this.displayedChatPosts.unshift(newPost);
				
				// 清空输入框
				this.newPostContent = '';
				
				// 关闭发布窗口
				this.showPublishWindow = false;
				
				uni.showToast({
					title: '发布成功',
					icon: 'success'
				});
			},
			
			// 从帖子联系用户
			chatWithUser(post) {
				// 检查该用户是否已在联系人列表中
				const userInfo = {
					id: post.id + 100, // 生成唯一ID
					name: post.username,
					avatar: post.avatar,
					lastMessage: '',
					lastTime: this.getCurrentTime(),
					unreadCount: 0
				};
				
				// 跳转到私聊页面
				uni.navigateTo({
					url: `/pages/chat/privateChat?contact=${encodeURIComponent(JSON.stringify(userInfo))}`
				});
			},
			
			// 获取当前时间
			getCurrentTime() {
				const now = new Date();
				return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
			},
			
			// 加载初始帖子数据
			loadInitialPosts() {
				// 如果有搜索关键词，则不加载初始数据
				if (this.searchKeyword.trim()) {
					return;
				}
				
				this.displayedChatPosts = this.chatPosts.slice(0, this.pageSize);
				this.displayedBookPosts = this.bookPosts.slice(0, this.pageSize);
				this.chatPage = 1;
				this.bookPage = 1;
			},
			
			// 下拉刷新
			onPullDownRefresh() {
				this.refreshing = true;
				setTimeout(() => {
					// 清除搜索关键词
					this.searchKeyword = '';
					this.loadInitialPosts();
					this.refreshing = false;
					uni.showToast({
						title: '刷新成功',
						icon: 'success'
					});
				}, 1000);
			},
			
			// 触底加载更多
			onReachBottom() {
				if (this.searchKeyword.trim()) {
					// 如果在搜索模式下，不加载更多
					return;
				}
				
				if (this.activeCategory === 'chat') {
					this.loadMoreChatPosts();
				} else {
					this.loadMoreBookPosts();
				}
			},
			
			// 加载更多闲聊区帖子
			loadMoreChatPosts() {
				if (this.chatLoading || this.displayedChatPosts.length >= this.chatPosts.length) return;
				
				this.chatLoading = true;
				this.chatLoadingText = '加载中...';
				
				setTimeout(() => {
					const start = this.chatPage * this.pageSize;
					const end = start + this.pageSize;
					const newPosts = this.chatPosts.slice(start, end);
					
					if (newPosts.length > 0) {
						this.displayedChatPosts = [...this.displayedChatPosts, ...newPosts];
						this.chatPage++;
					} else {
						this.chatLoadingText = '没有更多数据了';
					}
					
					this.chatLoading = false;
				}, 1000);
			},
			
			// 加载更多购书区帖子
			loadMoreBookPosts() {
				if (this.bookLoading || this.displayedBookPosts.length >= this.bookPosts.length) return;
				
				this.bookLoading = true;
				this.bookLoadingText = '加载中...';
				
				setTimeout(() => {
					const start = this.bookPage * this.pageSize;
					const end = start + this.pageSize;
					const newPosts = this.bookPosts.slice(start, end);
					
					if (newPosts.length > 0) {
						this.displayedBookPosts = [...this.displayedBookPosts, ...newPosts];
						this.bookPage++;
					} else {
						this.bookLoadingText = '没有更多数据了';
					}
					
					this.bookLoading = false;
				}, 1000);
			},
			
			// 显示帖子详情
			showPostDetail(post) {
				this.selectedPost = post;
				this.showDetail = true;
			},
			
			// 关闭帖子详情
			closePostDetail() {
				this.showDetail = false;
			}
		}
	}
</script>

<style lang="css" src="./chat_css.css" scoped>
page {
	background-color: #fff;
	min-height: 100%;
}
</style>

<style scoped>
/* 添加渐变背景色 */
.warp {
	background: linear-gradient(135deg, #CFDEF3 0%, #E0EAFC 100%);
	min-height: 100vh;
}

/* 搜索框样式 */
.search-container {
	display: flex;
	padding: 20rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #eee;
}

.search-input {
	flex: 1;
	height: 70rpx;
	padding: 0 20rpx;
	background-color: #f5f5f5;
	border-radius: 35rpx;
	font-size: 28rpx;
}

.search-button {
	width: 120rpx;
	height: 70rpx;
	margin-left: 15rpx;
	background: linear-gradient(135deg, #00d2ff 0%, #928DAB 100%);
	color: white;
	border-radius: 35rpx;
	font-size: 28rpx;
	font-weight: bold;
}

/* 悬浮发布按钮 */
.float-publish-btn {
	position: fixed;
	bottom: 50rpx;
	right: 50rpx;
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	background-color: #007AFF;
	display: flex;
	justify-content: center;
	align-items: center;
	box-shadow: 0 4rpx 20rpx rgba(0, 122, 255, 0.3);
	z-index: 999;
}

.float-publish-icon {
	font-size: 60rpx;
	color: white;
	font-weight: bold;
}

/* 发布窗口 */
.publish-window {
	position: fixed;
	bottom: -100%;
	right: 30rpx;
	width: 90%;
	max-width: 600rpx;
	background-color: white;
	border-radius: 20rpx;
	box-shadow: 0 4rpx 30rpx rgba(0, 0, 0, 0.15);
	z-index: 998;
	transition: bottom 0.3s ease;
	padding: 30rpx;
}

.publish-window.show {
	bottom: 150rpx;
}

.publish-window-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.publish-window-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.publish-window-close {
	font-size: 40rpx;
	color: #999;
}

.message-input {
	width: 100%;
	min-height: 150rpx;
	background-color: #f5f5f5;
	border-radius: 10rpx;
	padding: 15rpx;
	font-size: 28rpx;
	margin-bottom: 15rpx;
}

.post-button {
	width: 100%;
	height: 80rpx;
	line-height: 80rpx;
	background-color: #007AFF;
	color: white;
	border-radius: 10rpx;
	font-size: 30rpx;
}
</style>